# -*- coding: utf-8 -*-
#
# File: Acao.py
#
# Copyright (c) 2006 by IBICT
# Generator: ArchGenXML Version 1.5.0
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

__author__ = """IBICT <cadu@ibict.br>"""
__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from Products.Archetypes.SQLStorage import *
from Products.SIGFS.config import *

# additional imports from tagged value 'import'
from Products.DataGridField.DataGridField import DataGridField
from Products.DataGridField.DataGridWidget import DataGridWidget

##code-section module-header #fill in your manual code here
from Products.Archetypes import transaction
##/code-section module-header

schema = Schema((

    StringField(
        name='eixo',
        index="FieldIndex",
        serchable="1",
        required=1,
        vocabulary='getEixos',
        enforceVocabulary=1,
        widget=SelectionWidget(
            label="Eixo",
            description="Informe o Eixo ao qual a Ação será associada. Este é o eixo do plano estratégico do MCT.",
            format="select",
            label_msgid='SIGFS_label_eixo',
            description_msgid='SIGFS_help_eixo',
            i18n_domain='SIGFS',
        )
    ),

    DataGridField(
        name='recursos',
        serchable="1",
        required=1,
        widget=DataGridWidget(
            label="Recursos dos Fundos Setoriais",
            description="Informe os recursos que cada Fundo Setorial alocará para a Ação. Deve ser informado o custo total estimado por ano (R$ milhões).",
            column_names=('Fundo Setorial', '2007', '2008', 'Total',),
            label_msgid='SIGFS_label_recursos',
            description_msgid='SIGFS_help_recursos',
            i18n_domain='SIGFS',
        ),
        columns=('nome', 'ano1', 'ano2', 'total',)
    ),

    DataGridField(
        name='outros_recursos',
        serchable="1",
        widget=DataGridWidget(
            label="Outras Fontes",
            description="Informe os recursos que estas outras fontes alocarão para a Ação. Deve ser informado o custo total estimado por ano (R$ milhões)",
            column_names=('Nome', '2007', '2008', 'Total',),
            label_msgid='SIGFS_label_outros_recursos',
            description_msgid='SIGFS_help_outros_recursos',
            i18n_domain='SIGFS',
        ),
        columns=('nome', 'ano1', 'ano2', 'total',)
    ),

    ReferenceField(
        name='propostas',
        widget=ReferenceWidget(
            addable="1",
            label="Propostas",
            description="Selecione a proposta que está relacionada a esta Ação.",
            format="select",
            label_msgid='SIGFS_label_propostas',
            description_msgid='SIGFS_help_propostas',
            i18n_domain='SIGFS',
        ),
        allowed_types=('Proposta',),
        multiValued=1,
        relationship='acao_proposta'
    ),

    ReferenceField(
        name='agrupadores',
        widget=ReferenceWidget(
            addable="1",
            label="Agrupadores",
            description="Selecione o agrupador que deste nível.",
            format="select",
            label_msgid='SIGFS_label_agrupadores',
            description_msgid='SIGFS_help_agrupadores',
            i18n_domain='SIGFS',
        ),
        allowed_types=('Agrupador',),
        multiValued=1,
        relationship='acao_agrupador'
    ),

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

Acao_schema = BaseFolderSchema.copy() + \
    schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class Acao(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'Ação'

    meta_type = 'Acao'
    portal_type = 'Acao'
    allowed_content_types = ['Subacao']
    filter_content_types = 1
    global_allow = 0
    content_icon = 'treeCollapsed.gif'
    immediate_view = 'base_view'
    default_view = 'base_view'
    suppl_views = ()
    typeDescription = "Ação Transversal"
    typeDescMsgId = 'description_edit_acao'

    _at_rename_after_creation = True

    schema = Acao_schema

    ##code-section class-header #fill in your manual code here
    ##/code-section class-header

    # Methods

    # Manually created methods

    security.declarePrivate('_renameAfterCreation')
    def _renameAfterCreation(self, check_auto_id=False):
        """Renomeia o objeto com id numérico sequencial de 6 casas decimais."""
	parent_ids = self.aq_inner.aq_parent.objectIds()
        try:
          new_id = 'ac'+'%0.4i' % len(parent_ids)
          # Usando o portal_factory tem que comitar a subtransacao
          transaction.savepoint(optimistic=True)
	  self.setId(new_id)
	except:
	  new_id = 'ac'+'%0.4i' % len(parent_ids) + str(random.randint(1,1000))
          # Usando o portal_factory tem que comitar a subtransacao
          transaction.savepoint(optimistic=True)
	  self.setId(new_id)

    def getEixos(self):
        """Retorna a lista de Eixos."""
        portal_sigfs = getToolByName(self, 'portal_sigfs')
        result = []
        vocabulary = portal_sigfs.getVocab_eixo()

        for item in vocabulary:
            parts = item.split(';')
            result.append([parts[0], parts[1]])

        return DisplayList(tuple(result))



registerType(Acao, PROJECTNAME)
# end of class Acao

##code-section module-footer #fill in your manual code here
##/code-section module-footer



